package com.wutianyi.entity;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

public class FileServices {

	public static void saveFile(String fileName, byte[] datas)
			throws UnsupportedEncodingException {

		Entity fileEntity = new Entity("file", fileName);
		List<Entity> entities = new ArrayList<Entity>();
		entities.add(fileEntity);
		String[] dataStrs = new String(datas, "gbk").split("\n|\r\n");
		if (null != dataStrs && 0 < dataStrs.length) {

			int index = 0;

			Entity header = new Entity("header", "header", fileEntity.getKey());
			header.setUnindexedProperty("values", Arrays.asList(dataStrs[index].split(",")));

			entities.add(header);

			for (++index; index < dataStrs.length; index++) {
				Entity row = new Entity("row", fileEntity.getKey());
				String[] rowDatas = dataStrs[index].split(",");
				row.setUnindexedProperty("values", Arrays.asList(rowDatas));
				row.setProperty("index", rowDatas[0]);
				entities.add(row);
			}
		}
		DatastoreServiceFactory.getDatastoreService().put(entities);

	}
}
